<!-- 出货检验单管理 -->
<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="出货检验单编号" prop="oqcCode">
        <el-input
          v-model="queryParams.oqcCode"
          placeholder="请输入出货检验单编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="来源单据编号" prop="sourceDocCode">
        <el-input
          v-model="queryParams.sourceDocCode"
          placeholder="请输入来源单据编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="客户名称" prop="customerName">
        <el-input
          v-model="queryParams.customerName"
          placeholder="请输入客户名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="产品编码" prop="productCode">
        <el-input
          v-model="queryParams.productCode"
          placeholder="请输入产品编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="产品名称" prop="productName">
        <el-input
          v-model="queryParams.productName"
          placeholder="请输入产品名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="检测结果" prop="checkResult">
        <el-select v-model="queryParams.checkResult" placeholder="请选择检测结果" clearable>
          <el-option label="合格" value="1" />
          <el-option label="不合格" value="2" />
          <el-option label="待检" value="3" />
        </el-select>
      </el-form-item>
      <el-form-item label="检测日期" prop="inspectDate">
        <el-date-picker clearable
          v-model="queryParams.inspectDate"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择检测日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="单据状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择单据状态" clearable>
          <el-option label="草稿" value="1" />
          <el-option label="已提交" value="2" />
          <el-option label="已审核" value="3" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['ldzl-qc:oqc:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['ldzl-qc:oqc:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['ldzl-qc:oqc:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['ldzl-qc:oqc:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="oqcList"
      @selection-change="handleSelectionChange"
      border
      size="mini"
      style="width: 100%"
      :row-style="getRowStyle"
      :cell-style="{padding: '0px'}"
      :header-cell-style="{height: '40px', padding: '0px'}"
    >
      <el-table-column type="selection" width="55" align="center" fixed="left" />
      <el-table-column label="出货检验单ID" align="center" prop="oqcId" />
      <el-table-column label="出货检验单编号" align="center" prop="oqcCode" fixed="left"  width="120">
        <template slot-scope="scope">
          <el-link type="primary" :underline="false" @click="handleViewDetail(scope.row)">{{ scope.row.oqcCode }}</el-link>
        </template>
      </el-table-column>
      <el-table-column label="出货检验单名称" align="center" prop="oqcName" />
      <el-table-column label="来源单据类型" align="center" prop="sourceDocType">
        <template slot-scope="scope">
          <el-tag type="primary" v-if="scope.row.sourceDocType == 1">出货单</el-tag>
          <span v-else>{{scope.row.sourceDocType}}</span>
        </template>
      </el-table-column>
      <el-table-column label="来源单据编号" align="center" prop="sourceDocCode" />
      <el-table-column label="客户编码" align="center" prop="customerCode" />
      <el-table-column label="客户名称" align="center" prop="customerName" />
      <el-table-column label="批次号" align="center" prop="batchCode" />
      <el-table-column label="产品编码" align="center" prop="productCode" />
      <el-table-column label="产品名称" align="center" prop="productName" />
      <el-table-column label="产品规格型号" align="center" prop="productSfn" />
      <el-table-column label="单位" align="center" prop="unit" />
      <el-table-column label="发货数量" align="center" prop="quantityOutNum" />
      <el-table-column label="本次检测数量" align="center" prop="quantityCheckNum" />
      <el-table-column label="不合格数" align="center" prop="quantityUnqualifiedNum" />
      <el-table-column label="合格数量" align="center" prop="quantityQuanlifiedNum" />
      <el-table-column label="检测结果" align="center" prop="checkResult">
        <template slot-scope="scope">
          <el-tag type="success" v-if="scope.row.checkResult == 1">合格</el-tag>
          <el-tag type="danger" v-else-if="scope.row.checkResult == 2">不合格</el-tag>
          <el-tag type="warning" v-else-if="scope.row.checkResult == 3">待检</el-tag>
          <span v-else>{{scope.row.checkResult}}</span>
        </template>
      </el-table-column>
      <el-table-column label="出货日期" align="center" prop="outDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.outDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="检测日期" align="center" prop="inspectDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.inspectDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="单据状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status == 1">草稿</el-tag>
          <el-tag type="info" v-else-if="scope.row.status == 2">已提交</el-tag>
          <el-tag type="success" v-else-if="scope.row.status == 3">已审核</el-tag>
          <span v-else>{{scope.row.status}}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="250" fixed="right">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleViewDetail(scope.row)"
            v-hasPermi="['qc:OutgoingInspection:view']"
          >查看</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['qc:OutgoingInspection:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['qc:OutgoingInspection:remove']"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-warning"
            @click="handleDefectRecord(scope.row)"
            v-hasPermi="['qc:OutgoingInspection:view']"
          >缺陷记录</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 出货检验单表单组件弹窗 -->
    <el-dialog :title="title" :visible.sync="open" width="80%" :close-on-click-modal="false" :before-close="cancel" append-to-body>
      <oqc-form
        ref="oqcForm"
        :visible.sync="open"
        :title="title"
        :oqcId="oqcId"
        @success="handleSuccess"
        @cancel="cancel"
      />
    </el-dialog>

    <!-- 缺陷记录对话框 -->
    <defect-record-dialog
      :visible.sync="defectDialogVisible"
      title="出货检验单缺陷记录"
      :qcId="currentDefectOqcId"
      :qcType="3"
    />
  </div>
</template>

<script>
import { listOqc, delOqc } from "@/api/qc/OutgoingInspection"
import OqcForm from "./components/oqcForm"
import DefectRecordDialog from "../components/DefectRecordDialog"

export default {
  name: "Oqc",
  components: {
    OqcForm,
    DefectRecordDialog
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 出货检验单表格数据
      oqcList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 当前编辑的出货检验单ID
      oqcId: null,
      // 缺陷记录对话框显示状态
      defectDialogVisible: false,
      // 当前操作的缺陷记录相关的出货检验单ID
      currentDefectOqcId: null,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        oqcCode: null,
        oqcName: null,
        sourceDocType: null,
        sourceDocCode: null,
        customerName: null,
        productCode: null,
        productName: null,
        checkResult: null,
        inspectDate: null,
        status: null,
      },
      // 待检高亮ID
      highlightId: null
    }
  },
  created() {
    // 检查路由参数，获取检验单编号
    if (this.$route.query.inspectionCode) {
      // 使用检验单编号作为唯一查询条件
      this.queryParams.oqcCode = this.$route.query.inspectionCode;

      // 清空其他可能干扰查询的条件，确保查询精度
      Object.keys(this.queryParams).forEach(key => {
        if (key !== 'oqcCode' && key !== 'pageNum' && key !== 'pageSize') {
          this.queryParams[key] = null;
        }
      });

      this.$message.info('正在查找待检测单据，请稍候...');
    }
    this.getList();
  },
  methods: {
    /** 查询出货检验单列表 */
    getList() {
      this.loading = true;
      listOqc(this.queryParams).then(response => {
        // 确保返回的数据是数组
        this.oqcList = Array.isArray(response.rows) ? response.rows : [];
        this.total = response.total || 0;

        // 如果使用了检验单编号查询，尝试找到对应记录并高亮显示
        if (this.$route.query.inspectionCode) {
          // 安全检查 - 确保oqcList是数组且不为空
          if (this.oqcList && this.oqcList.length > 0) {
            const foundItem = this.oqcList.find(item => item && item.oqcCode === this.$route.query.inspectionCode);
            if (foundItem && foundItem.oqcId) {
              // 记录ID用于高亮显示
              this.highlightId = foundItem.oqcId;

              this.$message.success('找到待检测单据，已高亮显示');
              // 滚动到对应行（通过DOM操作，延迟确保表格已渲染）
              this.$nextTick(() => {
                try {
                  const rows = document.querySelectorAll('.el-table__row');
                  if (rows && rows.length > 0) {
                    // 安全遍历行
                    rows.forEach((row, index) => {
                      if (index < this.oqcList.length &&
                          this.oqcList[index] &&
                          this.oqcList[index].oqcId == this.highlightId) {
                        row.scrollIntoView({ behavior: 'smooth', block: 'center' });
                      }
                    });
                  }
                } catch (error) {
                  console.error('滚动到高亮行时出错:', error);
                }
              });
            } else {
              // 未找到时，给出明确的提示，并提供查询建议
              this.$message.warning({
                message: '未找到指定编号的检验单，请尝试调整查询条件',
                duration: 5000
              });

              // 自动重置查询，重新获取完整列表，便于用户手动查找
              this.$confirm('是否重置查询条件，显示所有检验单?', '提示', {
                confirmButtonText: '是',
                cancelButtonText: '否',
                type: 'info'
              }).then(() => {
                this.resetQuery();
              }).catch(() => {});
            }
          } else {
            this.$message.warning({
              message: '查询结果为空，未找到任何检验单',
              duration: 5000
            });
          }
        }
      }).catch(error => {
        console.error("获取列表失败:", error);
        this.$modal.msgError("数据加载失败");
        this.oqcList = []; // 确保发生错误时列表被重置为空数组
      }).finally(() => {
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.oqcId = null
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      // 清除高亮ID，因为用户主动搜索了
      this.highlightId = null;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      // 清除高亮ID
      this.highlightId = null;
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.oqcId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.oqcId = null
      this.open = true
      this.title = "添加出货检验单"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      // 清除高亮状态，因为要进入修改模式
      this.highlightId = null;

      this.oqcId = row.oqcId || this.ids[0];
      this.open = true;
      this.title = "修改出货检验单";
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const rqc = row || {};
      const oqcIds = row.oqcId || this.ids

      
      

      // 检查检测结果是否为待检
      if (rqc.checkResult !== 3 && rqc.checkResult !== '3') {
        this.$modal.msgError("只能删除检测结果为待检的单据");
        return;
      }
      this.$modal.confirm('是否确认删除出货检验单编号为"' + oqcIds + '"的数据项？').then(function() {
        return delOqc(oqcIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('ldzl-qc/oqc/export', {
        ...this.queryParams
      }, `oqc_${new Date().getTime()}.xlsx`)
    },
    /** 打开缺陷记录对话框 */
    handleDefectRecord(row) {
      if (!row || !row.oqcId) {
        this.$modal.msgWarning("无效的出货检验单ID");
        return;
      }
      this.currentDefectOqcId = row.oqcId;
      this.defectDialogVisible = true;
    },
    /** 处理表单提交成功 */
    handleSuccess(row) {
      // 关闭表单
      this.open = false;
      this.oqcId = null;

      // 直接刷新列表
      this.getList();
    },
    /** 查看详情 */
    handleViewDetail(row) {
      if (!row || !row.oqcId) {
        this.$modal.msgWarning("无效的出货检验单ID");
        return;
      }
      this.$router.push({
        path: `/qc/OutgoingInspection/detail/${row.oqcId}`
      });
    },
    // 获取行样式
    getRowStyle(row) {
      const baseStyle = {height: '40px'};
      // 确保row和row.row存在且有效
      if (this.highlightId && row && row.row && row.row.oqcId == this.highlightId) {
        return {
          ...baseStyle,
          backgroundColor: '#fdf5e6', // 淡黄色背景
          fontWeight: 'bold',
          color: '#ff7800'
        };
      }
      return baseStyle;
    }
  }
}
</script>

<style scoped>
.el-tag {
  padding: 2px 8px;
}

.el-link.el-link--primary {
  font-weight: bold;
  font-size: 14px;
}

.el-link.el-link--primary:hover {
  color: #409EFF;
  text-decoration: underline !important;
}

/* 优化固定列样式 */
::v-deep .el-table__fixed-right {
  height: 100% !important;
}

::v-deep .el-table__fixed-left {
  height: 100% !important;
}

::v-deep .el-table__row td {
  height: 40px !important;
}

/* 确保所有单元格内容垂直居中 */
::v-deep .el-table .cell {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
}

/* 调整按钮单元格内容样式 */
::v-deep .el-table .cell .el-button {
  padding: 3px 0;
  margin: 0 3px;
}

/* 高亮待检行样式 */
.highlight-row {
  background-color: #fdf5e6 !important;
  font-weight: bold;
  color: #ff7800;
}
</style>
